package xyz.lisys.zuul.fallback;

import lombok.NonNull;
import lombok.val;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ServerFallbackProvider implements FallbackProvider {

    @Override
    public String getRoute() {
        return "entry";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {

            @Override
            @NonNull
            public HttpHeaders getHeaders() {
                val httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
                return httpHeaders;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return getStatusCode().value();
            }

            @Override
            @NonNull
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            @Override
            @NonNull
            public String getStatusText() throws IOException {
                return getStatusCode().getReasonPhrase();
            }

            @Override
            @NonNull
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("{\"message\":\"服务不可用\"}".getBytes());
            }

            @Override
            public void close() {
            }
        };
    }
}
